<template>
  <div class="container">
    <div class="fixed-header">
      <div class="wrong-list"><span>错题列表</span><span >（共查出<i>{{ wrongQuesSum }}</i>道题）</span></div>
    </div>
    <cus-skeleton :loading="loading">
      <div class="section">
        <div class="item" v-for="data in dataset" :key="data.id">
          <div class="content-text">
            <div class="title" v-html="data.title"></div>
            <div v-question="data"></div>
          </div>
          <div class="flex-box" v-show="showAnswer">
            <div class="label">答案</div>
            <div class="flex-main" v-html="data.answer"></div>
          </div>
          <div class="flex-box" v-show="data.showAnalysis">
            <div class="label">解析</div>
            <div class="flex-main">
              <span v-html="data.analysis" v-if="data.analysis" />
              <span v-else>暂无解析</span>
            </div>
          </div>
          <div class="flex-box" v-show="data.showAnalysis">
            <div class="label">知识点</div>
            <div class="flex-main">
              <span v-if="data.knowledges">{{ filterKnowle(data) }}</span>
              <span v-else>暂无知识点</span>
            </div>
          </div>
          <div class="footer">
            <p>{{ data.questionTypeName }}</p>
            <p>
              <span>错误时间：</span><span>{{ data.createTime }}</span>
            </p>
            <p>
              <span>难度：</span><span>{{ data.difficult }}</span>
            </p>
            <p>
              <span>引用：</span><span>{{ data.useCount || 0 }}</span>
            </p>
            <div>
              <p><i @click="data.showAnalysis = !data.showAnalysis">解析</i></p>
              <!-- <p><i @click="similarPreview(data.id)">相似题</i></p> -->
              <a class="cart-icon" @click.prevent="addCart(data)" :class="{ active: !!cartList.find((i) => i.id === data.id) }" />
            </div>
          </div>
        </div>

        <template v-if="!dataset.length && !loading">
          <cus-empty />
        </template>
        <template v-if="dataset.length && !loading">
          <el-pagination
            v-model:current-page="pageAorder.current"
            v-model:page-size="pageAorder.size"
            :total="pageAorder.total"
            @current-change="request(searchParams)"
            layout="prev, pager, next"
          />
        </template>
      </div>
    </cus-skeleton>
  </div>

  <TestBasketComponent :question-list="cartList" />
</template>

<script lang="ts">
import { ref, Ref, reactive, computed, onMounted, nextTick } from "vue";
import { useStore } from "vuex";
import TestBasketComponent from "@/views/question/components/test-basket.vue";
import QuestionDirective from "@/views/utils/question.directive";
import $, { emitter } from "$";
const difficultFilter = (v) =>
  [
    { name: "易", id: 11 },
    { name: "较易", id: 12 },
    { name: "中档", id: 13 },
    { name: "较难", id: 14 },
    { name: "难", id: 15 },
  ].find((i) => i.id === v)?.name;

export default {
  props: {
    searchParams: {
      type: Object,
      default: () => ({})
    }
  },
  components: { TestBasketComponent },
  directives: { question: QuestionDirective },
  setup(props) {
    onMounted(() => {
      emitter.on("selection-change", () => {
        pageAorder.current = 1;
      });
      emitter.on("remove-questionBase", (data) => {
        $.clone(cartList.value).forEach((qus: any) => {
          if (qus.type == data) {
            addCart(qus);
          }
        });
      });
      emitter.on("clear-questionBase", () => {
        $.clone(cartList.value).forEach((qus: any) => {
          addCart(qus);
        });
      });
    });
    let store = useStore();
    let userId = computed(() => store.getters.userInfo.user.id);
    let dataset: Ref<any[]> = ref([]);
    // let dataSet = computed(() => dataset.value.map(data => {
    //   data.createTime = moment(new Date(data.createTime)).format('YYYY-MM-DD');
    //   return data;
    // }))

    let showAnswer = ref(false);

    let pageAorder = reactive({
      current : 1,
      size    : 10,
      total   : 0
    });


    let __params: any = {};

    let loading = ref(false);
    let wrongQuesSum = ref()
    const request = async (params?) => {
      loading.value = true;
      params && (__params = params);
      let res
      if (!params.currentIndex) {
        res = await $.http.json(`/admin/userErrorQuestion/queryPagePC`, { ...__params, ...pageAorder, });  
        if (res.result) {
          dataset.value = res.json.records.map((n) => ({
            ...n.question,
            ...{
              errorCount: n.questionCount,
              createTime: n.createTime.split("-").join("/").split(" ")[0],
              difficult: difficultFilter(n.question.difficult),
              answer: n.question.rightAnswer ? n.question.rightAnswer.map((a, index) => {
                  if (n.question.basicQuestionType !== 3) {
                    return a[n.question.basicQuestionType === 1 ? "name" : "content"];
                  }
                  return `<div style="display:flex">（${index + 1}）${a[n.question.basicQuestionType === 1 ? "name" : "content"]}</div>`;
                }).join('') : '-',
            },
          }));
          pageAorder.total = res.json.total;
          wrongQuesSum.value = res.json.total
        }
      } else {
        res = await $.http.json(`/admin/lessonSummaryDetails/queryWrongQuestionPage`, { ...__params, ...pageAorder, });
        if (res.result) {
          dataset.value = res.json.records.map((n) => ({
            ...n,
            ...{
              createTime: n.createTime.split("-").join("/").split(" ")[0],
              difficult: difficultFilter(n.difficult),
              answer: n.rightAnswer ? n.rightAnswer.map((a, index) => {
                  if (n.basicQuestionType !== 3) {
                    return a[n.basicQuestionType === 1 ? "name" : "content"];
                  }
                  return `<div style="display:flex">（${index + 1}）${a[n.basicQuestionType === 1 ? "name" : "content"]}</div>`;
                }).join('') : '-',
            },
          }));
          pageAorder.total = res.json.total;
          wrongQuesSum.value = res.json.total
        }
      }
    
      loading.value = false;
      nextTick(() => {
        let container = document.querySelector('.section-main');
        container && (container.scrollTop = 0);
      });
    }
    console.log(props.searchParams)
    $.emitter.on('question-request',() => request(props.searchParams))
    /* ------------- 查看相似题 ------------- */
    const similarPreview = async (id) => {
      let res = await $.http.post("/tiku/question/querySimilar", { id, subject: __params.subject, count: 10 });
    };

    let cartList: Ref<any[]> = ref($.storage.get('cartListValue') || []);

    const addCart = (data) => {
      let index = cartList.value.findIndex(d => d.id === data.id);
      index > -1 ? cartList.value.splice(index, 1)  : cartList.value.push(data);
      $.storage.set('cartListValue', cartList.value);
    };
    const filterSource = (data) => {
      if (!data.questionSources) { return; }
      let { yearName, provinceName, cityName, areaName, publicSchoolName, dictSourceName, } = data.questionSources[0];
      return Object.values({
        yearName,
        provinceName,
        cityName,
        areaName,
        publicSchoolName,
        dictSourceName,
      }).join('');
    };
    const filterKnowle = (data) => {
      if (!data.knowledges) { return; }
      return data.knowledges.map(ele => ele.name).join(',');
    };
    return { request, loading, dataset, pageAorder, similarPreview, showAnswer, userId, cartList, addCart, filterSource, filterKnowle, wrongQuesSum };
  },
};
</script>

<style lang="scss" scoped>
.container {
  flex: auto;
  display: flex;
  flex-direction: column;
  margin-top: 15px;
  height: 100%;
  & > .fixed-header {
    padding: 0 28px;
    color: #fff;
    line-height: 34px;
    background: #72b22a;
    border-radius: 6px 6px 0px 0px;
    .wrong-list {
      & > :nth-child(1) {
        font-size: 16px;
        margin-right: 4px;
      }
      & > :nth-child(2) {
        i {
          color: #faad14;
        }
      }
    }
  }
  .section {
    flex: 1 1 36px;
    background: #fff;
    padding: 20px 28px;
    .item {
      padding: 20px 20px 0;
      border-radius: 10px;
      border: 1px solid #ebeef6;
      position: relative;
      transition: all 0.25s;
      &.is__selected {
        cursor: pointer;
      }
      &.is__disabled {
        pointer-events: none;
        background: #f9f9f9;
      }
      &.is__checked {
        border-color: #19aea5;
      }
      &:not(:last-child) {
        margin-bottom: 20px;
      }
      &:hover {
        box-shadow: 0px 2px 11px 0px rgba(23, 18, 45, 0.2);
      }
      .title {
        margin-bottom: 20px;
      }
      .content-text {
        margin-right: 20px;
        overflow: hidden;
        img {
          display: inline-block;
        }
      }
      .flex-box {
        font-size: 13px;
        display: flex;
        margin-top: 14px;
        .label {
          display: inline-block;
          height: 20px;
          padding: 0 7px;
          color: #3abab3;
          font-size: 12px;
          line-height: 20px;
          background: rgba(58, 186, 179, 0.15);
          border-radius: 4px;
          margin-right: 8px;
          width: 50px;
          white-space: nowrap;
        }
        .flex-main {
          flex: auto;
          color: #77808d;
        }
      }
      .footer {
        height: 36px;
        margin: 20px -20px 0;
        font-size: 12px;
        line-height: 36px;
        background: #f2f1f6;
        border-bottom-left-radius: 8px;
        border-bottom-right-radius: 8px;
        border-top: solid 1px #ebf0fc;
        .error-btn {
          margin-left: 10px;
          color: $--color-danger;
          border-color: $--color-danger;
          background: #FFEFEB;
        }
        
        .footer-source {
          width: calc(100vw - 1200px);
          padding: 0;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        p {
          float: left;
          margin-left: 18px;
          color: #1a2633;
          span {
            color: #77808d;
          }
          i {
            color: #382a74;
            cursor: pointer;
            &:active {
              opacity: 0.6;
            }
          }
        }
        div {
          float: right;
          padding-right: 20px;
          a {
            display: inline-block;
            padding: 0 10px;
            margin-left: 20px;
            color: #72b22a;
            line-height: 20px;
            border: solid 1px #72b22a;
            border-radius: 12px;
            transition: all 0.25s;
            cursor: pointer;
            &.is__loading {
              pointer-events: none;
              opacity: 0.6;
            }
            &.cart-icon.active {
              color: #faad14;
              border: solid 1px #faad14;
              background: #fff7e9;
              &::before {
                content: "移出试题篮";
              }
            }
            &.cart-icon::before {
              content: "加入试题篮";
              display: inline-block;
            }
          }

          & > i {
            color: #5b7dff;
            font-size: 18px;
            line-height: 36px;
            margin-right: 20px;
            vertical-align: top;
            cursor: pointer;
            &:active {
              opacity: 0.8;
            }
          }
        }
      }
    }
  }
  
  :deep(.el-pagination) {
    text-align: right;
  }
}
:deep(.item) {
  .e-main {
    display: flex;
    flex-wrap: wrap;
    padding-left: 20px;
    .e-m-cell {
      display: flex;
      align-items: center;
      > img {
        margin-left: 5px;
      }
      &.w-1 {
        width: 100%;
      }
      &.w-2 {
        width: 50%;
      }
      &.w-4 {
        width: 25%;
      }
      margin-bottom: 10px;
      .e-c-label {
        width: 40px;
      }
      .e-c-group {
        flex: 1 1 40px;
        display: flex;
        flex-wrap: wrap;
        .c-t-item {
          flex: 1;
          white-space: nowrap;
        }
      }
    }
    &-title {
      .e-m-cell {
        margin-bottom: 20px;
        .e-c-label {
          margin-bottom: 5px;
        }
        .e-c-group {
          line-height: 24px;
          text-indent: 20px;
        }
      }
    }
  }
}
:deep(.el-button--mini) {
  min-height: 22px;
}
:deep(.el-button--mini.is-round) {
  padding: 2px 10px;
}
</style>
